package com.draven.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.draven.mall.entity.Product;
import com.draven.mall.mapper.ProductMapper;
import com.draven.mall.service.ProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品服务实现类
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Override
    public Map<String, Object> getProductPage(Long merchantId, Long categoryId, String keyword, Integer status, Integer page, Integer size) {
        // 默认分页参数
        page = (page == null || page < 1) ? 1 : page;
        size = (size == null || size < 1) ? 10 : size;
        
        // 创建分页对象
        Page<Product> pageParam = new Page<>(page, size);
        
        // 查询
        IPage<Product> pageResult = baseMapper.selectProductPage(pageParam, merchantId, categoryId, keyword, status);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        return result;
    }

    @Override
    public Product getProductById(Long id) {
        return getById(id);
    }

    @Override
    @Transactional
    public boolean addProduct(Product product) {
        // 设置初始值
        product.setSales(0); // 初始销量为0
        if (product.getStatus() == null) {
            product.setStatus(0); // 默认下架
        }
        product.setCreatedTime(new Date());
        product.setUpdatedTime(new Date());
        
        return save(product);
    }

    @Override
    @Transactional
    public boolean updateProduct(Product product) {
        // 首先查询商品是否存在，并检查是否属于该商家
        Product existingProduct = getById(product.getId());
        if (existingProduct == null || !existingProduct.getMerchantId().equals(product.getMerchantId())) {
            return false;
        }
        
        // 设置更新时间
        product.setUpdatedTime(new Date());
        
        return updateById(product);
    }

    @Override
    @Transactional
    public boolean deleteProduct(Long id, Long merchantId) {
        // 检查商品是否存在，并且属于该商家
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getId, id).eq(Product::getMerchantId, merchantId);
        long count = count(queryWrapper);
        
        if (count == 0) {
            return false;
        }
        
        return removeById(id);
    }

    @Override
    @Transactional
    public boolean updateProductStatus(Long id, Long merchantId, Integer status) {
        // 检查商品是否存在，并且属于该商家
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getId, id).eq(Product::getMerchantId, merchantId);
        long count = count(queryWrapper);
        
        if (count == 0) {
            return false;
        }
        
        // 更新状态
        LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Product::getId, id)
                     .set(Product::getStatus, status)
                     .set(Product::getUpdatedTime, new Date());
        
        return update(updateWrapper);
    }

    @Override
    public List<Product> getRecommendedProducts(Integer limit) {
        // 默认获取5个推荐商品
        limit = (limit == null || limit < 1) ? 5 : limit;
        
        // 查询状态为上架的商品，按销量降序排序，取前limit个
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getStatus, 1) // 状态为上架
                    .orderByDesc(Product::getSales) // 按销量降序
                    .last("LIMIT " + limit); // 限制数量
        
        return list(queryWrapper);
    }
} 